<template>
  <div class="split-pane-wrapper" ref="outre">
    <div class="pane pane-left" :style="{ width: leftOffsetPercent, paddingRight: `${this.triggerWidth / 2}px` }">
      <slot name="left"></slot>
    </div>
    <div class="pane-trigger-con" @mousedown="handleMouseDown" :style="{ left: triggerLeft, width: triggerWidth  }"></div>
    <div class="pane pane-right" :style="{ left: leftOffsetPercent, paddingLeft: `${this.triggerWidth / 2}px` }">
      <slot name="right"></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SplitPane',
  data () {
    return {
      canMove: false,
      initOffset: 0
    }
  },
  props: {
    value: {
      type: Number,
      default: 0.5
    },
    triggerWidth: {
      type: Number,
      default: 8
    },
    min: {
      type: Number,
      default: 0.1
    },
    max: {
      type: Number,
      default: 0.9
    }
  },
  computed: {
    leftOffsetPercent () {
      return `${this.value * 100}%`
    },
    triggerLeft () {
      return `calc(${this.value * 100}% - ${this.triggerWidth / 2}px)`
    }
  },
  methods: {
    handleClick () {
      this.value -= 0.02
    },
    handleMouseDown (event) {
      document.addEventListener('mousemove', this.handleMouseMove)
      document.addEventListener('mouseup', this.handleMouseUp)
      this.initOffset = event.pageX - event.srcElement.getBoundingClientRect().left
      this.canMove = true
    },
    handleMouseMove (event) {
      if(!this.canMove) return
      // this.$refs.outer.getBoundingClientRect() 操作当前容器距离对象
      // event.pageX 鼠标距页面左侧有多少像素
      const outerRect = this.$refs.outre.getBoundingClientRect()
      let offsetPercent = (event.pageX - this.initOffset +this.triggerWidth / 2 - outerRect.left) / outerRect.width
      if(offsetPercent < this.min) offsetPercent = this.min
      if(offsetPercent > this.max) offsetPercent = this.max
      //  this.$emit('input', offsetPercent)
      this.$emit('update:value', offsetPercent)
    },
    handleMouseUp () {
      this.canMove = false
    }
  }
}
</script>

<style lang="less">
.split-pane-wrapper{
  height: 100%;
  width: 100%;
  position: relative;
  .pane{
    position: absolute;
    top: 0;
    height: 100%;
    // &表示父级（.pane）此写法相当于 .pane-left
    &-left{
      /*<!--width: 20%;-->*/
      background: palevioletred;
    }
    &-right{
      right: 0;
      bottom: 0;
      /*<!--left: 20%;-->*/
      background: paleturquoise;
    }
    &-trigger-con{
      width: 8px;
      height: 100%;
      background: red;
      position: absolute;
      top: 0;
      z-index: 10;
      user-select: none;
      // css-cursor.techstream.org
      cursor: col-resize;
    }
  }
}
</style>
